#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
智能数据库配置工具
更换数据库地址时保留现有的微信等配置

用法:
python smart_db_setup.py --host 60.205.131.52 --port 3306 --user weixin --password XFnWNyK6ndypibCD --database weixin
"""

import argparse
import os
import sys
import re

def read_existing_config():
    """读取现有的.env配置"""
    config = {}
    if os.path.exists('.env'):
        with open('.env', 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    config[key] = value
    return config

def create_smart_env_file(host, port, user, password, database, preserve_config=None):
    """创建智能环境配置文件，保留现有配置"""
    if preserve_config is None:
        preserve_config = {}
    
    # 优先保留的配置项
    preserved_keys = [
        'WECHAT_APPID', 'WECHAT_SECRET',
        'SECRET_KEY', 'JWT_SECRET_KEY', 
        'WTF_CSRF_SECRET_KEY'
    ]
    
    env_content = f"""# 环境配置文件 - 智能生成
# 生成时间: {os.popen('date').read().strip()}
# 数据库更新，保留现有微信等配置

# Flask 环境配置
FLASK_ENV=development
SECRET_KEY={preserve_config.get('SECRET_KEY', 'your-super-secret-key-here-change-this-in-production')}

# 服务器配置
HOST=0.0.0.0
PORT=5000

# 数据库配置 - MySQL (已更新)
MYSQL_HOST={host}
MYSQL_PORT={port}
MYSQL_USER={user}
MYSQL_PASSWORD={password}
MYSQL_DATABASE={database}

# 数据库连接池配置
DB_POOL_SIZE=10
DB_POOL_TIMEOUT=20
DB_POOL_RECYCLE=3600
DB_MAX_OVERFLOW=0
DB_ECHO=false

# JWT配置 (保留现有)
JWT_SECRET_KEY={preserve_config.get('JWT_SECRET_KEY', 'jwt-secret-key-change-this-in-production')}
JWT_EXPIRES_HOURS=168

# 文件上传配置
UPLOAD_FOLDER=uploads
MAX_CONTENT_LENGTH=16777216

# 日志配置
LOG_LEVEL=INFO
LOG_FILE=logs/app.log

# 微信配置 (保留现有配置)
WECHAT_APPID={preserve_config.get('WECHAT_APPID', 'your-wechat-appid')}
WECHAT_SECRET={preserve_config.get('WECHAT_SECRET', 'your-wechat-secret')}

# 跨域配置
CORS_ORIGINS=http://localhost:8080,http://127.0.0.1:8080

# 微信支付配置
WECHAT_APP_ID={preserve_config.get('WECHAT_APP_ID', 'your-wechat-app-id')}
WECHAT_MCH_ID={preserve_config.get('WECHAT_MCH_ID', 'your-merchant-id')}
WECHAT_PAY_KEY={preserve_config.get('WECHAT_PAY_KEY', 'your-api-key')}
WECHAT_NOTIFY_URL={preserve_config.get('WECHAT_NOTIFY_URL', 'http://your-domain.com/api/v1/payments/wechat/notify')}

# Redis配置
REDIS_URL=redis://localhost:6379/0

# 安全配置 (保留现有)
WTF_CSRF_SECRET_KEY={preserve_config.get('WTF_CSRF_SECRET_KEY', 'csrf-secret-key-change-in-production')}
SEND_FILE_MAX_AGE_DEFAULT=31536000

# 开发模式配置
DEBUG=True
TESTING=False
"""
    
    # 写入.env文件
    with open('.env', 'w', encoding='utf-8') as f:
        f.write(env_content)
    
    return preserve_config

def test_connection(host, port, user, password, database):
    """测试数据库连接"""
    print("🔍 测试数据库连接...")
    
    try:
        import pymysql
        
        connection = pymysql.connect(
            host=host,
            port=int(port),
            user=user,
            password=password,
            database=database,
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
        
        connection.close()
        print("✅ 数据库连接测试成功")
        return True
        
    except ImportError:
        print("⚠️ PyMySQL 未安装，跳过连接测试")
        return True
        
    except Exception as e:
        print(f"❌ 数据库连接测试失败: {e}")
        return False

def main():
    parser = argparse.ArgumentParser(description='智能数据库配置工具 - 保留现有配置')
    parser.add_argument('--host', required=True, help='数据库地址')
    parser.add_argument('--port', default='3306', help='端口号 (默认: 3306)')
    parser.add_argument('--user', required=True, help='用户名')
    parser.add_argument('--password', required=True, help='密码')
    parser.add_argument('--database', required=True, help='数据库名')
    parser.add_argument('--no-test', action='store_true', help='跳过连接测试')
    parser.add_argument('--force', action='store_true', help='强制覆盖，不保留现有配置')
    
    args = parser.parse_args()
    
    print("🧠 智能数据库配置工具")
    print("=" * 50)
    print(f"数据库地址: {args.host}")
    print(f"端口: {args.port}")
    print(f"用户名: {args.user}")
    print(f"数据库名: {args.database}")
    
    # 读取现有配置
    existing_config = {}
    if not args.force and os.path.exists('.env'):
        existing_config = read_existing_config()
        print("\n📋 发现现有配置，将保留以下重要配置:")
        preserved_keys = ['WECHAT_APPID', 'WECHAT_SECRET', 'SECRET_KEY', 'JWT_SECRET_KEY']
        for key in preserved_keys:
            if key in existing_config and existing_config[key] not in ['', 'your-wechat-appid', 'your-wechat-secret']:
                if key.startswith('WECHAT'):
                    masked_value = existing_config[key][:8] + '****' + existing_config[key][-4:] if len(existing_config[key]) > 12 else '****'
                    print(f"  {key}: {masked_value}")
                else:
                    print(f"  {key}: ****")
    
    print("=" * 50)
    
    # 测试连接
    if not args.no_test:
        if not test_connection(args.host, args.port, args.user, args.password, args.database):
            print("❌ 连接测试失败，请检查数据库配置")
            sys.exit(1)
    
    # 创建配置文件
    preserved = create_smart_env_file(args.host, args.port, args.user, args.password, args.database, existing_config)
    
    print("\n🎉 智能数据库配置完成！")
    print("\n📋 更新的配置信息：")
    print(f"  MYSQL_HOST={args.host}")
    print(f"  MYSQL_PORT={args.port}")
    print(f"  MYSQL_USER={args.user}")
    print(f"  MYSQL_DATABASE={args.database}")
    
    if preserved:
        print("\n✅ 保留的重要配置：")
        important_keys = ['WECHAT_APPID', 'WECHAT_SECRET']
        for key in important_keys:
            if key in preserved and preserved[key] not in ['', f'your-{key.lower().replace("_", "-")}']:
                masked = preserved[key][:8] + '****' + preserved[key][-4:] if len(preserved[key]) > 12 else '****'
                print(f"  {key}: {masked}")
    
    print("\n🚀 下一步操作：")
    print("1. 重启服务: python run.py")
    print("2. 健康检查: curl http://localhost:5000/health")
    print("3. 测试微信配置: python test_wechat_config.py")

if __name__ == '__main__':
    main() 